using System;
using System.Collections.Generic;
using System.Linq;
using FireStarterModeller.BO;
using Habanero.Base;
using Habanero.BO;

namespace FireStarterModeller.Logic.Wizards
{
    public class DMPropertyDeleter : IDeleter
    {
        public IDMProperty DMProperty { get; private set; }


        public DMPropertyDeleter(IDMProperty dmProperty)
        {
            if (dmProperty == null) throw new ArgumentNullException("dmProperty");
            this.DMProperty = dmProperty;
        }

        /// <summary>
        /// Deletes the DMProperty and all its Related Business Objects
        /// </summary>
        public void Delete()
        {
            MarkForDelete();
            this.DMProperty.Save();
        }
        /// <summary>
        /// Marks the DMProperty and any of its RelatedProperties, UCProperties
        /// and UIProps.
        /// </summary>
        public void MarkForDelete()
        {
            var relPropsForSimpleRelationships = this.DMProperty.RelationshipProperties.Where(IsSimpleRelationshipFk);
            foreach (var relationshipProperty in relPropsForSimpleRelationships.ToList())
            {
                relationshipProperty.Relationship.MarkForDelete();
            }

            var relPropsToBeDeleted = this.DMProperty.RelationshipProperties.ToArray();
            foreach (var relationshipProperty in relPropsToBeDeleted)
            {
                relationshipProperty.MarkForDelete();
            }
            var ucPropsToBeDeleted = this.DMProperty.DMUniqueConstraintProperties.ToArray();
            foreach (var uniqueConstraintProperty in ucPropsToBeDeleted)
            {
                uniqueConstraintProperty.MarkForDelete();
            }
            DMProperty currentDMProperty = (DMProperty) this.DMProperty;

            var uiPropsToDelete = currentDMProperty.UIProps.ToArray();

            foreach (var uiProp in uiPropsToDelete)
            {
                uiProp.MarkForDelete();
            }


            this.DMProperty.MarkForDelete();
        }

        private static bool IsSimpleRelationshipFk(DMRelationshipProperty relProp)
        {
            if (relProp.Relationship == null) return false;
            return relProp.Relationship.RelationshipProperties.Count == 1;
        }
    }
}